package com.example.mallsystem1104.controller;

import com.example.mallsystem1104.annotation.Authority;
import com.example.mallsystem1104.common.Result;
import com.example.mallsystem1104.constants.Constants;
import com.example.mallsystem1104.entity.AuthorityType;
import com.example.mallsystem1104.entity.Avatar;
import com.example.mallsystem1104.service.AvatarService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;

/**
 * @Author zy
 * @Date 2024/12/12 15:22
 * @packageName:com.example.mallsystem1104.controller
 * @ClassName:AvatarController
 */
@RestController
@RequestMapping("/avatar")
public class AvatarController {
    @Resource
    private AvatarService avatarService;

    /**
     * 上传头像
     * @param file
     * @return
     */
    @PostMapping
    public Result uploadAvatar(@RequestBody MultipartFile file){
        String url=avatarService.upload(file);
        return Result.success(url);
    }

    @GetMapping("/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response){
        avatarService.download(fileName,response);
    }

    //根据id删除头像文件
    @Authority(AuthorityType.requireAuthority)
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable int id){
        int i=avatarService.delete(id);
        if (i==1){
            return Result.success();
        }else {
            return Result.error(Constants.CODE_500,"删除失败");
        }
    }

    @GetMapping("page")
    public Result selectPage(
            @RequestParam int pageNum,
            @RequestParam int pageSize
    ){
        int index=(pageNum-1)*pageSize;
        List<Avatar> avatars=avatarService.selectPage(index,pageSize);
        int total=avatarService.getTotal();
        HashMap<String,Object> map=new HashMap<>();
        map.put("records",avatars);
        map.put("total",total);
        return Result.success(map);
    }

}
